#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""网关列表"""
import asyncio
import json
import os
import time
from datetime import datetime
from time import sleep
import requests
from dotenv import load_dotenv
import common
import db

mysqldb = db.DbManager()
load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('ADMIN')
passworld = os.getenv('PWD')


# 获取登录后cookie
async def get_cookie(page):
    cookies_list = await page.cookies()
    cookies = ''
    for cookie in cookies_list:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    print(cookies)
    return cookies


def list_split(items, n):
    return [items[i:i + n] for i in range(0, len(items), n)]


def curl():
    cookie_str = "JSESSIONID=C800668DDA71827B670F50DD8D216AFE;"
    cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
    data = {
        'start': 0,
        'limit': 100,
        'unitid': '4028fc8a7075cd2d017075d216b30006',
    }
    headers = {
        'referer': 'http://210.12.220.207:8003/adp/home/sensor/blank.jsp?modeindex=m101',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
    }
    resp = requests.post(
        "http://210.12.220.207:8003/adp/gate/getAllGate",
        headers=headers, cookies=cookies, data=data,timeout=20)
    print("----------")
    print(resp)
    print("----------")
    json_text = json.loads(resp.text)
    print(json_text)
    list_html = json_text['data']
    print(len(list_html))
    time.sleep(2)
    for i in range(0, len(list_html)):
        # 查询是否存在 codeName
        list_html_list = list_html[i]
        codeName = ""
        if list_html_list['productionlink'] != None:
            resp_code = requests.get(
                "http://210.12.220.207:8003/adp/dictionary/getByProductionlink?productionlink=" + list_html_list[
                    'productionlink'],
                headers=headers, cookies=cookies)
            print(resp_code)
            json_text_code = json.loads(resp_code.text)
            print(json_text_code)
            codeName = json_text_code['data'][0]['name']

        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        info = {"gate_id": list_html_list['id'], "unitid": list_html_list['unitid'],
                "device_name": list_html_list['name'],
                "adapter": list_html_list['adapter'],
                "adapterid": list_html_list['adapterid'],
                "phone": list_html_list['phone'],
                "deviceid": list_html_list['deviceid'],
                "device_sn": list_html_list['sng'],
                "devicenum": list_html_list['devicenum'],
                "ip": list_html_list['ip'],
                "port": list_html_list['port'],
                "sng": list_html_list['sng'],
                "notes": list_html_list['notes'],
                "lon": list_html_list['jd'],
                "lat": list_html_list['wd'],
                "status": list_html_list['state'],
                "gate_create": list_html_list['createtime'],
                "gate_update": list_html_list['updatetime'],
                "unitname": list_html_list['unitname'],
                "province": list_html_list['province'],
                "provinceId": list_html_list['provinceId'],
                "productionlink": list_html_list['productionlink'],
                "cityId": list_html_list['cityId'],
                "countyId": list_html_list['countyId'],
                "codeName": codeName,
                "address": list_html_list['name'].split('-')[0],
                }
        print(info)
        find_info = mysqldb.table_select_one(table='devices_info', field="id",
                                             where={"gate_id": list_html_list['id']})
        # 存在数据则跳过
        if find_info:
            # 更新
            info['update_date'] = now_time
            mysqldb.table_update(table="devices_info", data=info,
                                 where="gate_id ='" + list_html_list['id'] + "'")
        else:
            # 添加
            info['create_date'] = now_time
            mysqldb.table_insert(table='devices_info', data=info)
    sleep(1)


class Egas:
    def __init__(self):
        self.url = "http://210.12.220.207:8003/adp/gate/getAllGate"
        # sql = 'SELECT i.orgId FROM devices_info where device_sn is null order by id desc limit 500'
        # mysqldb.execute(sql)
        # self.org_ids=mysqldb.cur.fetchall()
        asyncio.get_event_loop().run_until_complete(self.main())

    async def main(self):
        curl()


Egas()
